package com.ruoyi.system.utils;

import com.ruoyi.system.anno.SnowflakeId;

import java.lang.reflect.Field;

public class SnowflakeIdProcessor {
    private static final SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);

    public static void process(Object object) {
        Class<?> clazz = object.getClass();
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            if (field.isAnnotationPresent(SnowflakeId.class)) {
                SnowflakeId annotation = field.getAnnotation(SnowflakeId.class);
                SnowflakeIdGenerator generator = new SnowflakeIdGenerator(
                        annotation.datacenterId(),
                        annotation.machineId()
                );

                try {
                    field.setAccessible(true);
                    if (field.get(object) == null) {
                        field.set(object, generator.nextId());
                    }
                } catch (IllegalAccessException e) {
                    throw new RuntimeException("Failed to set snowflake ID", e);
                }
            }
        }
    }
}
